package com.fourth.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * @author Mr.ma
 * @since 2023/3/11 14:56
 **/
@Configuration
public class RabbitConfiguration {
    public static final String QUEUE_NAME = "queue_name_pay";
    public static final String EXCHANGE_NAME = "exchange_name_pay";
    public static final String ROUTING_KEY = "routing_key_pay";
    public static final String DLX_QUEUE_NAME = "dlx_queue_name_pay";
    public static final String DLX_EXCHANGE_NAME = "dlx_exchange_name_pay";
    public static final String DLX_ROUTING_KEY = "dlx_routing_key_pay";

    /**
     * 死信队列
     * @return
     */
    @Bean
    Queue dlxQueue() {
        return new Queue(DLX_QUEUE_NAME, true, false, false);
    }

    /**
     * 死信交换机
     * @return
     */
    @Bean
    DirectExchange dlxExchange() {
        return new DirectExchange(DLX_EXCHANGE_NAME, true, false);
    }

    /**
     * 绑定死信队列和死信交换机
     * @return
     */
    @Bean
    Binding dlxBinding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange())
                .with(DLX_ROUTING_KEY);
    }

    /**
     * 普通消息队列
     * @return
     */
    @Bean
    Queue Queue() {
        Map<String, Object> args = new HashMap<>(16);
        //设置消息过期时间
        args.put("x-message-ttl", 1000*60*30);
        //设置死信交换机
        args.put("x-dead-letter-exchange", DLX_EXCHANGE_NAME);
        //设置死信 routing_key
        args.put("x-dead-letter-routing-key", DLX_ROUTING_KEY);
        return new Queue(QUEUE_NAME, true, false, false, args);
    }

    /**
     * 普通交换机
     * @return
     */
    @Bean
    DirectExchange Exchange() {
        return new DirectExchange(EXCHANGE_NAME, true, false);
    }

    /**
     * 绑定普通队列和与之对应的交换机
     * @return
     */
    @Bean
    Binding Binding() {
        return BindingBuilder.bind(Queue())
                .to(Exchange())
                .with(ROUTING_KEY);
    }
}

